package cn.com.headfree.welfare.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.TOrgDept;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.welfare.entity.FlIod;
import cn.com.headfree.welfare.entity.Vo.CharstVo;
import cn.com.headfree.welfare.entity.Vo.PTRVo;
import cn.com.headfree.welfare.entity.Vo.TOrgDeptVo;
import cn.com.headfree.welfare.entity.Vo.XztxVo;
import cn.com.headfree.welfare.service.FlIodService;
import cn.com.headfree.welfare.service.FlNcsgsxdjhService;
import cn.com.headfree.welfare.service.FlPtrService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 福利模块
 * 福利模块控制器
 * @author makejava
 * @since 2021-12-19 15:14:50
 */
@RestController
@RequestMapping("Welfare")
public class WelfareController extends ExBaseController {
    private static final Logger LOG = LogManager.getLogger(WelfareController.class);
    /**
     * 服务对象
     */
    @Resource
    private FlIodService flIodService;
    @Resource
    private FlNcsgsxdjhService flNcsgsxdjhService;

    /**
     * 服务对象
     */
    @Resource
    private FlPtrService flPtrService;

    /**
     * 获取表图
     * @param time
     * @param request
     * @return
     */
    @PostMapping("getCharts")
    public ResultData getCharts(String time, HttpServletRequest request,String orgId) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            Map<String,Object> map=new HashMap<>();
            String [] X=new String[] {"合计","独生子女费","抚恤费","食堂经费","福利机构经费","福利机构维修费","折旧费","医疗费",
            "医疗费1：因公外地就医费","医疗费2：职工体检费","职工疗养费","职工困难补助","探亲假路费","离退休统筹外费用","离退休统筹外费用1：一次性生活补贴",
            "离退休统筹外费用2：医疗费","退休医疗费","离休医疗费","离退休统筹外费用3：困难补助","离退休统筹外费用4：活动经费"};

            String [] name=new String[] {"合计","独生子女费","抚恤费","食堂经费","福利经费","机构经费","折旧费","医疗费",
                    "外地就医费","职工体检费","疗养费","困难补助费","探亲路费","统筹外费用","生活补贴",
                    "医疗费","退休医疗费","离休医疗费","困难补助","活动经费"};
            if(time==null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                time=sdf.format(new Date());
            }
            String [] Xs=new String[] {
                    "zjhj",
                    "dsznf",
                    "fxf",
                    "stjf",
                    "fljgjf",
                    "fljgWxf",
                    "fljgZjf",
                    "ylf",
                    "ylfYgwdjyf",
                    "ylfZgtjf",
                    "zglyf",
                    "zgknbz",
                    "tqjlf",
                    "ltxtcwfy",
                    "ltxtcwfyYcxshbt",
                    "ltxtcwfyYlf",
                    "ltxtcwfyYlfTxylf",
                    "ltxtcwfyYlfLxylf",
                    "ltxtcwfyKnbz",
                    "ltxtcwfyHdjf"};
            //计划同申报调整相比增减情况
            CharstVo iod= this.flIodService.selectIOP(time,orgId);
            //申请调整计划情况
            CharstVo adj= this.flIodService.selectADJ(time,orgId);
            //年初省公司下达计划情况表
            CharstVo ncs= this.flIodService.selectNCS(time,orgId);
            //下一年度申报计划表
            CharstVo Next= this.flIodService.selectNext(time,orgId);

            List<String> iodArr=new ArrayList<>();
            List<String> adjArr=new ArrayList<>();
            List<String> ncsArr=new ArrayList<>();
            List<String> NextArr=new ArrayList<>();

            for(int i=0;i< Xs.length;i++){
                try {
                    iodArr.add(getValues(Xs[i],iod));
                }catch (Exception e){
                    LOG.info("计划同申报调整相比增减情况"+Xs[i]+"为空");
                }
                try {
                    adjArr.add(getValues(Xs[i],adj));
                }catch (Exception e){
                    LOG.info("申请调整计划情况"+Xs[i]+"为空");
                }
                try {
                    ncsArr.add(getValues(Xs[i],ncs));
                }catch (Exception e){
                    LOG.info("年初省公司下达计划情况表"+Xs[i]+"为空");
                }
                try {
                    NextArr.add(getValues(Xs[i],Next));
                }catch (Exception e){
                    LOG.info("下一年度申报计划表"+Xs[i]+"为空");
                }

            }
            map.put("X",X);
            map.put("name",name);
            map.put("iod",iodArr);
            map.put("adj",adjArr);
            map.put("ncs",ncsArr);
            map.put("Next",NextArr);

            result.setSuccess(true);
            result.setData(map);

        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }


    public static String  getValues(String language,Object  obj) {
        Object returnStr=null;
        Field languageFiled;
        try {
            languageFiled = obj.getClass().getDeclaredField(language);
            languageFiled.setAccessible(true);
            returnStr =  languageFiled.get(obj);

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return  returnStr==null?"":returnStr.toString();
    }

    /**
     * 获取人员调动list
     * @param ptrVo
     * @param request
     * @return
     */
    @PostMapping("getRydd")
    public ResultData getRydd(PTRVo ptrVo,HttpServletRequest request){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            List<PTRVo> list=new ArrayList<>();
            for(int i=0;i<10;i++){
                PTRVo ptrVo1=new PTRVo();
                ptrVo1.setId(Long.getLong(String.valueOf(i)));
                ptrVo1.setDrdw(String.valueOf(i));
                list.add(ptrVo1);
            }
            PageInfo<PTRVo> pageInfo = new PageInfo<>(list);
            result.setSuccess(true);
            result.setData(pageInfo);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result ;
    }

    /**
     * 修改人员调动
     * @param ptrVo
     * @param request
     * @return
     */
    @PostMapping("deitRydd")
    public ResultData deitRydd(PTRVo ptrVo,HttpServletRequest request){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            result.setSuccess(true);
            result.setData(ptrVo);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result ;
    }

    /**
     * 获取新增退休list
     * @param ptrVo
     * @param request
     * @return
     */
    @PostMapping("getXztxVo")
    public ResultData getXztxVo(XztxVo ptrVo, HttpServletRequest request){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            List<XztxVo> list=new ArrayList<>();
            for(int i=0;i<10;i++){
                XztxVo ptrVo1=new XztxVo();
                ptrVo1.setId(Long.getLong(String.valueOf(i)));
                ptrVo1.setName(String.valueOf(i));
                ptrVo1.setTime(new Date());
                ptrVo1.setSsdwmc("测试单位");
                list.add(ptrVo1);
            }
            PageInfo<XztxVo> pageInfo = new PageInfo<XztxVo>(list);
            result.setSuccess(true);
            result.setData(pageInfo);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result ;
    }

    /**
     * 修改新增退休
     * @param ptrVo
     * @param request
     * @return
     */
    @PostMapping("deitXztxVo")
    public ResultData deitXztxVo(XztxVo ptrVo,HttpServletRequest request){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {

            result.setSuccess(true);
            result.setData(ptrVo);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result ;
    }

    /**
     * 导出EXECL文件
     * @param response
     * @param name (tx 退休人员 ，dd 调动人员)
     */
    @GetMapping("/downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response,String name) {

        SimpleDateFormat formatYYYY = new SimpleDateFormat("YYYYMMdd");
        String fileName ="";
        Map<String,Object> map1 = new HashMap<String, Object>() ;
        String filePath = "";
        switch (name) {
            case "tx":
                // 下载文件能正常显示中文
                fileName="人员退休统计_"+formatYYYY.format(new Date())+".xlsx";
                filePath = "templates/XztxVo.xlsx";

                //导出数据
                List<XztxVo> list=new ArrayList<>();
                for(int i=0;i<10;i++){
                    XztxVo ptrVo1=new XztxVo();
                    ptrVo1.setSsdwmc("测试单位");
                    ptrVo1.setName(String.valueOf(i));
                    ptrVo1.setTime(new Date());
                    list.add(ptrVo1);
                }
                map1.put("list",list);
                break;
            case "dd":
                // 下载文件能正常显示中文
                fileName="人员调动_"+formatYYYY.format(new Date())+".xlsx";
                filePath = "templates/PTRVo.xlsx";
                //导出数据
                List<PTRVo> list1=new ArrayList<>();
                for(int i=0;i<10;i++){
                    PTRVo ptrVo1=new PTRVo();
                    ptrVo1.setErpId(String.valueOf(i));
                    ptrVo1.setName(String.valueOf(i));
                    ptrVo1.setYdwmc("测试原单位");
                    ptrVo1.setDrdw("测试调入单位");
                    ptrVo1.setDdTime(new Date());
                    list1.add(ptrVo1);
                }
                map1.put("list",list1);
                break;
        }
        try{
            // 获取导出excel指定模版
            System.out.println("生成模板文件");
            //获取项目的根目录
            String rootPath = System.getProperty("user.dir");
            //创建临时的模板存放文件
            String path = rootPath +"/" +filePath;
            System.out.println("存放模板目录及模板文件：："+path);
            File file = new File(path);
            if(!file.exists()){
                System.out.println("不存在则创建文件："+path);
                ClassPathResource resource = new ClassPathResource(filePath);
                InputStream inputStream = resource.getInputStream();
                saveTempFile(inputStream,file);
                System.out.println("模板创建成功!");
            }
            TemplateExportParams params = new TemplateExportParams(path,true);
            // 导出excel
            System.out.println("生产execl");
            // 存放数据map
            Workbook workbook= ExcelExportUtil.exportExcel(params , map1 );
            downLoadExcel(fileName,response,workbook);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static void saveTempFile(InputStream inputStream, File tempFile) throws IOException {
        //如果文件的目录不存在
        if(!tempFile.getParentFile().exists()){
            //创建父目录
            tempFile.getParentFile().mkdirs();
        }
        OutputStream os = new FileOutputStream(tempFile);
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        os.flush();
        os.close();
        inputStream.close();
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        // 写出数据输出流到页面
        try {
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入模板下载
     * @param request
     * @param response
     * @param easyName
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/mouldDownload")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response,@RequestParam String easyName)	throws UnsupportedEncodingException {
        String filePath = "";
        // 下载文件能正常显示中文
        String fileName = "";
        Map<String,Object> map1 = new HashMap<String, Object>() ;
        switch (easyName){
            case "fl_nc":
                filePath = "/templates/年初省公司下达计划情况表模板.xls";
                fileName= "年初省公司下达计划情况表模板.xls";
                break;
            case "fl_xyn":
                filePath = "/templates/下一年度申报计划表.xls";
                fileName= "下一年度申报计划表.xls";
                break;
            case "fl_sqtz":
                filePath = "/templates/申请调整计划情况表.xls";
                fileName= "申请调整计划情况表.xls";
                break;
            case "fl_jhts":
                filePath = "/templates/计划同申报调整相比增减情况表.xls";
                fileName= "计划同申报调整相比增减情况表.xls";
                break;
        }
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {

            String deptid=get3DeptId(user.getBaseOrgId());

            user.setBaseOrgId(deptid);

            List<TOrgDeptVo> depts = flNcsgsxdjhService.getDeptsByOrgId(user);
            List<String> dataList = depts.stream().map(TOrgDeptVo::getName).collect(Collectors.toList());
            map1.put("deptName",dataList.get(0).toString());
            try{
                // 获取导出excel指定模版
                System.out.println("生成模板文件");
                //获取项目的根目录
                String rootPath = System.getProperty("user.dir");
                //创建临时的模板存放文件
                String path = rootPath +"/" +filePath;
                System.out.println("存放模板目录及模板文件：："+path);
                File file = new File(path);
                if(!file.exists()){
                    System.out.println("不存在则创建文件："+path);
                    ClassPathResource resource = new ClassPathResource(filePath);
                    InputStream inputStream = resource.getInputStream();
                    saveTempFile(inputStream,file);
                    System.out.println("模板创建成功!");
                }
                TemplateExportParams params = new TemplateExportParams(path,true);
                // 导出excel
                System.out.println("生产execl");
                // 存放数据map
                Workbook workbook= ExcelExportUtil.exportExcel(params , map1 );
                selectList(workbook, 6, 65535, 0, 0, dataList.toArray(new String[dataList.size()]), 1);
                downLoadExcel(fileName,response,workbook);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            return "获取统一权限用户信息异常";
        }
        return null;
    }


    private String get3DeptId(String orgId){
        TOrgDept depts = flNcsgsxdjhService.getPdeptid(orgId);
        String re="";
        if(depts==null){
            return null;
        }
        if(Integer.valueOf(depts.getLevel())>2){
            re=get3DeptId(depts.getpId());
        }else {
            if(depts.getName().indexOf("公司")<0){
                re= get3DeptId(depts.getpId());
            }else {
                re=depts.getId();
            }
        }
        return re;
    }
    /**
     * firstRow 开始行号(下标0开始)
     * lastRow  结束行号，最大65535
     * firstCol 区域中第一个单元格的列号 (下标0开始)
     * lastCol 区域中最后一个单元格的列号
     * dataArray 下拉内容
     * sheetHidden 影藏的sheet编号（例如1,2,3），多个下拉数据不能使用同一个
     * */
    public static void selectList(Workbook workbook, int firstRow, int lastRow, int firstCol, int lastCol, String[] dataArray, int sheetHidden){
        String hiddenName = "hidden_" + (int)((Math.random()*9+1)*100);
        Sheet sheet = workbook.getSheetAt(0);
        Sheet hidden = workbook.createSheet(hiddenName);
        Cell cell = null;
        for (int i = 0, length = dataArray.length; i < length; i++)
        {
            String name = dataArray[i];
            Row row = hidden.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(name);
        }

        Name namedCell = workbook.createName();
        namedCell.setNameName(hiddenName);
        namedCell.setRefersToFormula(hiddenName + "!$A$1:$A$" + dataArray.length);
        //加载数据,将名称为hidden的
        DVConstraint constraint = DVConstraint.createFormulaListConstraint(hiddenName);

        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        HSSFDataValidation validation = new HSSFDataValidation(addressList, constraint);

        // 将sheet设置为隐藏
        workbook.setSheetHidden(sheetHidden, true);
        sheet.addValidationData(validation);
    }



    }
